### function

function StringStartWith()
{
    if [ $# -ne 2 ]; then
        throw_exception_with_file_and_line
        exit 1
    fi

    echo "${1}" | grep -iE "^${2}"
    return $?
}

# AbsoluteDir
#
# $1:       input dir
# #ret:     none
# $echo:    output absolute dir
#
function AbsoluteDir()
{
    if [ $# -ne 1 ]; then
        throw_exception_with_file_and_line
        exit 1
    fi

    old_dir=$(pwd)
    cd ${1}
    echo $(pwd)
    cd ${old_dir}
}

function ScriptDir()
{
    if [ $# -ne 1 ]; then
        throw_exception_with_file_and_line
        exit 1
    fi

    echo `AbsoluteDir ${0%/*}`
}


###
CLANG_BIN_DIR="/x/_build_tools/llvm/llvm-project-16.0.4.src/ci-llvm-project-16.0.4.src/_deploy/x64d/bin";

SCRIPT_DIR=$(ScriptDir "$0")
SCRIPT_DIR_NAME=${SCRIPT_DIR##/*/}
PARENT_DIR="${SCRIPT_DIR%/*}"
BUILD_DIR="${PARENT_DIR}/${SCRIPT_DIR_NAME}-ci/libfuzzer_clang_step_with_dll/_build/x64d"

echo "SCRIPT_DIR:       ${SCRIPT_DIR}"
echo "SCRIPT_DIR_NAME:  ${SCRIPT_DIR_NAME}"
echo "PARENT_DIR:       ${PARENT_DIR}"
echo "BUILD_DIR:        ${BUILD_DIR}"



### lib

LIB_SOURCE_CPP_NAKED_NAMES=(
    constant
    bingo
    impl
)

declare -A LIB_SOURCE_OBJ_FPS
for fn in ${LIB_SOURCE_CPP_NAKED_NAMES[*]}; do
    LIB_SOURCE_OBJ_FPS[$fn]=${BUILD_DIR}/${fn}.obj
done

echo -e "\n\n\n==> -c"
for fn in ${LIB_SOURCE_CPP_NAKED_NAMES[*]}; do
    mkdir -p ${BUILD_DIR}; \
    cd ${BUILD_DIR}; \
    "${CLANG_BIN_DIR}/clang++.exe" \
    -v \
    -g \
    -O0 \
    -c \
    -fsanitize=address,fuzzer,fuzzer-no-link \
    -I ${SCRIPT_DIR}/include \
    -o ${fn}.obj \
    ${SCRIPT_DIR}/src/${fn}.cpp \
    || exit 1
done

echo -e "\n\n\n==> -o"

mkdir -p ${BUILD_DIR}; \
cd ${BUILD_DIR}; \
"${CLANG_BIN_DIR}/clang++.exe" \
-v \
-g \
-O0 \
-fsanitize=address,fuzzer,fuzzer-no-link \
-shared \
-o imp.dll \
${LIB_SOURCE_OBJ_FPS[*]} \
|| exit 1


### exe

echo -e "\n\n\n==> -o"

mkdir -p ${BUILD_DIR}; \
cd ${BUILD_DIR}; \
"${CLANG_BIN_DIR}/clang++.exe" \
-v \
-g \
-O0 \
-fsanitize=address,fuzzer \
-I ${SCRIPT_DIR}/include \
-l imp.lib \
-o jc_first_fuzz_sample.exe \
${SCRIPT_DIR}/src/main.libfuzzer.cpp \
|| exit 1

###
echo ""
pwd
ls

###
echo ""
mkdir -p ./_out; \
cd ./_out; \
rm -rf ./*; \
../jc_first_fuzz_sample.exe "${SCRIPT_DIR}/_in" -jobs=1000000
